class_name AnimationComponent
extends BaseComponent

#region 属性
var animation_finished_callback_dict:Dictionary = {}
#endregion
#region 字段
var sprite_2d:Sprite2D:
	get:
		if not sprite_2d:
			sprite_2d = %Sprite2D
		return sprite_2d
var animation_player:AnimationPlayer:
	get:
		if not animation_player:
			animation_player = %AnimationPlayer
		return animation_player
#endregion
#region 信号
signal anim_finished(anim_name: StringName)
#endregion

#region 基类方法
func init_component(args:Dictionary = {}):
	super(args)
	animation_player.animation_finished.connect(_on_anim_finished)
#endregion
#region 公共方法
func get_animation(anim_name:String) -> Animation:
	var anim:Animation = animation_player.get_animation(anim_name)
	return anim if anim else null
func play_animation(name: String, custom_blend: float = -1, custom_speed: float = 1.0, from_end: bool = false):
	animation_player.play(name,custom_blend,custom_speed,from_end)
func stop_animation(name:String,keep_state: bool = false):
	if animation_player.current_animation == name:
		animation_player.stop(keep_state)
func add_animation(anim_name:String,animation:Animation):
	if animation_player:
		var library:AnimationLibrary = animation_player.get_animation_library("")
		if library and not library.has_animation(anim_name):
			library.add_animation(anim_name,animation.duplicate(true))
func remove_animation(anim_name:String):
	if animation_player:
		var library:AnimationLibrary = animation_player.get_animation_library("")
		if library and library.has_animation(anim_name):
			if animation_player.current_animation == anim_name:
				animation_player.stop()
			library.remove_animation(anim_name)
func add_call_method_track_and_method(anim_name:String,time:float,method_name:String,args:Array,bind_obj:Node) -> AddCallMethodTrackRes:
	return Utils.add_call_method_track_and_method(animation_player,anim_name,time,method_name,args,bind_obj)
func register_anim_finished_event(anim_name:String,callback:Callable,connect_flag:ConnectFlags = 0):
	var anim:Animation = animation_player.get_animation(anim_name)
	if anim and not animation_finished_callback_dict.has(callback):
		var final_callback = func(cur_anim_name: StringName):
			if anim_name == cur_anim_name:
				callback.call()
		animation_finished_callback_dict[callback] = final_callback
		animation_player.animation_finished.connect(final_callback,connect_flag)
func unregister_anim_finished_event(anim_name:String,callback:Callable):
	var anim:Animation = animation_player.get_animation(anim_name)
	if anim and animation_finished_callback_dict.has(callback) and animation_player.animation_finished.is_connected(animation_finished_callback_dict[callback]):
		animation_player.animation_finished.disconnect(animation_finished_callback_dict[callback])
		animation_finished_callback_dict.erase(callback)
#endregion
#region 私有方法
func _on_anim_finished(anim_name: StringName):
	anim_finished.emit(anim_name)
#endregion
#region 生命周期函数
#endregion
